package cn.ricecode.mybatis.controller;

import cn.ricecode.mybatis.util.ZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * @author LiuZhulan
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    public final String FILENAME = "E:\\a.png";

    public final String PATH = "";

    public final String filePath = "C:\\Users\\liuzlan\\Desktop\\ricecode.txt";

    public final String fileName = "ricecode.txt";

    /**
     * 下载一个txt文件，使用传入HttpServletResponse的方式
     * @param response
     */
    @RequestMapping("/download")
    public void downloadTxt(HttpServletResponse response) {

        response.setHeader("Content-Type", MediaType.APPLICATION_OCTET_STREAM.toString());
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
        File file = new File(filePath);
        try {
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
            OutputStream os = response.getOutputStream();
            byte[] buffer = new byte[1024];
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            log.info("下载文件成功");
        } catch (Exception e) {
            log.info("{}", e);
        }

    }

    /**
     * 载一个txt文件，使用返回ResponceEntity的方式
     * @return
     */
    @RequestMapping("/downloadWithEntity")
    public ResponseEntity<Resource> downloadWithResponseEntity() {

        File file = new File(filePath);
        ContentDisposition contentDisposition=ContentDisposition.builder("attachment")
                .filename(file.getName(),StandardCharsets.UTF_8)
                .build();
        HttpHeaders headers=new HttpHeaders();
        headers.setContentDisposition(contentDisposition);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

        try {
            return ResponseEntity.ok().headers(headers).body(new InputStreamResource(FileUtils.openInputStream(file)));
        } catch (IOException e) {
            log.info("{}", e);
            return null;
        }

    }

    /**
     * 下载zip文件
     * @return
     */
    @RequestMapping("/downloadZip")
    public ResponseEntity<Resource> downloadZip(){
        File origin = new File(filePath);
        File file = ZipUtils.zipFiles(fileName, Arrays.asList(origin));
        ContentDisposition contentDisposition=ContentDisposition.builder("attachment")
                .filename(file.getName(),StandardCharsets.UTF_8)
                .build();
        HttpHeaders headers=new HttpHeaders();
        headers.setContentDisposition(contentDisposition);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try {
            return ResponseEntity.ok().headers(headers).body(new InputStreamResource(FileUtils.openInputStream(file)));
        } catch (IOException e) {
            log.info("{}", e);
            return null;
        }finally {
            //deleteQuietly方法删除的文件，可以为空，如果删除失败，就是该文件被其他程序占用了
            boolean deleteQuietly = FileUtils.deleteQuietly(file);
            if (!deleteQuietly) {
                /**
                 *  当调用delete()方法时，直接删除文件，不管该文件是否存在，一经调用立即执行
                 *  当调用deleteOnExit()方法时，只是相当于对deleteOnExit（）作一个声明，
                 *  当程序运行结束，JVM终止时才真正调用deleteOnExit()方法实现删除操作。即该方法是将删除的命令缓存了一下，到服务停止的时候再进行操作！
                 */
                file.deleteOnExit();
            }
            log.info("删除文件{},结果：{}", file.getName(), deleteQuietly);
        }
    }

    /**
     * 合成图片，压缩返回
     * 1、OSS获取的图片字节数组，转成BufferedImage去合成
     * 2、返回合成后的BufferImages
     * 3、BufferImages写入到文件
     */
    public void downloadImages(){

    }


}
